﻿using ETModel;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

namespace ETHotfix {
    /// <summary>
    /// 单位根据寻路结果进行移动,附加给Unit即可使用
    /// </summary>
	public class UnitPathComponent : Component
	{
		public List<Vector3> Path = new List<Vector3>();

		public Vector3 ServerPos;

		public CancellationTokenSource CancellationTokenSource;
		
		public async ETTask StartMove(CancellationToken cancellationToken, float speed)
		{
			for (int i = 0; i < this.Path.Count; ++i)
			{
				Vector3 v = this.Path[i];
                float movePerSec = speed;

                if (i == 0)
				{
					// 矫正移动速度
					Vector3 clientPos = this.GetParent<Unit>().Position;
					float serverf = (ServerPos - v).magnitude;
					if (serverf > 0.1f)
					{
						float clientf = (clientPos - v).magnitude;
                        movePerSec = clientf / serverf * speed;
					}
				}

				this.Entity.GetComponent<TurnComponent>().Turn(v);
				await this.Entity.GetComponent<MoveComponent>().MoveToAsync(v, movePerSec, cancellationToken);
			}
		}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="startPos"></param>
        /// <param name="movePath"></param>
        /// <param name="speed">每秒移动的距离</param>
        /// <returns></returns>
		public async ETTask StartMove(Vector3 startPos, List<Vector3> movePath, float speed)
		{
			// 取消之前的移动协程
			this.CancellationTokenSource?.Cancel();
			this.CancellationTokenSource = new CancellationTokenSource();

			ServerPos = startPos;
            Path = movePath;

            await StartMove(this.CancellationTokenSource.Token, speed);
			this.CancellationTokenSource.Dispose();
			this.CancellationTokenSource = null;
        }

        public void EndMove() {
            this.CancellationTokenSource?.Cancel();
            this.CancellationTokenSource = null;
        }
	}
}